<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 警示框 -->
            <el-alert title="编辑商品信息" type="info" show-icon :closable="false" center>
            </el-alert>
            <br>
            <!-- 步骤条 -->
            <el-steps :active="activeIndex - 0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <br>
            <!-- 标签页 -->
            <el-form :model="editGoodsForm" :rules="editGoodsFormRules" ref="editGoodsFormRef" label-position="top">
                <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeTabsLeave"
                    @tab-click="tabClicked">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="editGoodsForm.goods_name" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="editGoodsForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_number">
                            <el-input v-model="editGoodsForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_weight">
                            <el-input v-model="editGoodsForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <!-- 级联选择器 -->
                            <el-cascader v-model="editGoodsForm.goods_cat" :options="goodsCateList"
                                :props="goodsCateProps" @change="goodsCateChange" clearable filterable></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <!-- 表单item项 -->
                        <el-form-item :label="item.attr_name" v-for="item in goodsManyData" :key="item.attr_id">
                            <!-- 复选框组 -->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox :label="lableItem" v-for="(lableItem, i) in item.attr_vals" :key="i"
                                    border>
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="item in goodsOnlyData" :key="item.attr_id">
                            <el-input v-model="item.attr_vals" clearable></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
                            list-type="picture" :headers="headersObj" :on-success="handleSuccess"
                            :file-list="editGoodsForm.pics">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 富文本编辑器 -->
                        <quill-editor v-model="editGoodsForm.goods_introduce"></quill-editor>
                        <br>
                        <!-- 编辑商品按钮 -->
                        <el-button type="primary" @click="edit">编辑商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>

        <!-- 图片预览的对话框 -->
        <el-dialog title="图片预览" :visible.sync="picPerviewDialogVisible" width="50%">
            <img :src="picPerviewPath" width="100%">
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 步骤条、标签页默认激活的索引
            activeIndex: '0',
            // 编辑商品表单数据绑定对象
            editGoodsForm: {
                goods_name: '', // 商品名称
                goods_price: '', // 商品价格
                goods_number: '', // 商品重量
                goods_weight: '', // 商品数量
                goods_cat: [], // 商品分类
                pics: [], // 商品图片
                goods_introduce: '', // 商品介绍
                attrs: [] // 商品的参数
            },
            // 编辑商品表单验证规则对象
            editGoodsFormRules: {
                goods_name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' }
                ],
                goods_price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' }
                ],
                goods_number: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' }
                ],
                goods_weight: [
                    { required: true, message: '请输入商品数量', trigger: 'blur' }
                ],
                goods_cat: [
                    { required: true, message: '请选择商品分类', trigger: 'blur' }
                ],
            },
            // 商品信息
            goodsInfo: [],
            // 商品分类列表
            goodsCateList: [],
            // 商品分类的配置对象
            goodsCateProps: {
                expandTrigger: 'hover',
                label: 'cat_name',
                value: 'cat_id',
                children: 'children'
            },
            // 选中的商品分类数据Id
            goods_cat: [],
            // 商品动态参数
            goodsManyData: [],
            // 商品静态属性
            goodsOnlyData: [],
            // 上传图片的URL地址
            uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
            // 上传图片的headers请求头
            headersObj: {
                Authorization: window.sessionStorage.getItem('token'),
            },
            // 预览图片的路径
            picPerviewPath: '',
            // 图片预览对话框的显示与隐藏
            picPerviewDialogVisible: false,
            // 图片数组
            picsData: [],
            // 商品id
            goodsId: 0,
        }
    },
    created() {
        // 获取Goods组件传过来的商品Id
        this.goodsId = this.$route.query.goods_id;
        // 获取商品信息
        this.getGoodsInfo(this.goodsId);
        // 获取商品分类数据
        this.getGoodsCateData();
    },
    methods: {
        // 获取商品信息
        async getGoodsInfo(goodsId) {
            const { data: res } = await this.$http.get('goods/' + goodsId);
            if (res.meta.status !== 200) return this.$message.error('获取商品信息失败');
            // 将商品分类从字符串转为数组，并从字符数组转为数字数组
            res.data.goods_cat = res.data.goods_cat.split(',').map(Number);
            // 处理图片
            res.data.pics.forEach(item => {
                const newPicObj = {
                    name: item.pics_sma,
                    url: item.pics_sma_url
                }
                this.picsData.push(newPicObj);
            })
            this.editGoodsForm = res.data;
            this.editGoodsForm.pics = this.picsData;
        },
        // 获取商品分类数据
        async getGoodsCateData() {
            const { data: res } = await this.$http.get('categories');
            if (res.meta.status !== 200) return this.$message.error('获取商品分类数据失败');
            this.goodsCateList = res.data;
        },
        // 商品分类选项改变时触发
        goodsCateChange() {
            if (this.editGoodsForm.goods_cat.length !== 0 && this.editGoodsForm.goods_cat.length !== 3) {
                this.editGoodsForm.goods_cat = [];
                this.$message.info('只允许选择第三级分类');
            }
        },
        // 切换标签之前的钩子
        beforeTabsLeave(activeName, oldActiveName) {
            // 基本信息切换
            if (oldActiveName === '0') {
                // 需要校验的字段
                let fieldsToValidate = ['goods_name', 'goods_price', 'goods_number', 'goods_weight', 'goods_cat'];
                // 校验
                Promise.all(
                    fieldsToValidate.map((field) => {
                        return new Promise((resolve, reject) => {
                            this.$refs['editGoodsFormRef'].validateField(field, (errorMessage) => {
                                resolve(errorMessage);
                            });
                        });
                    })
                ).then((errorMessages) => {
                    // errorMessages 里是各个字段的验证错误信息, 如果数组里全为空串则所有验证通过
                    // 判断errorMessages 里是否全是空串
                    let valid = errorMessages.every((errorMessage) => {
                        return errorMessage == '';
                    });
                    if (!valid) {
                        this.activeIndex = oldActiveName;
                        this.$message.info('请先完成基本信息的填写！');
                    }
                });
            }
        },
        // tab栏被点击
        async tabClicked() {
            if (this.activeIndex === '1') {
                if (this.cateId) {
                    const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                        params: { sel: 'many' }
                    })
                    if (res.meta.status !== 200) return this.$message.error('商品参数获取失败');
                    res.data.forEach(item => {
                        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
                    })
                    this.goodsManyData = res.data;
                }
            } else if (this.activeIndex === '2') {
                if (this.cateId) {
                    const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                        params: { sel: 'only' }
                    })
                    if (res.meta.status !== 200) return this.$message.error('商品属性获取失败');
                    this.goodsOnlyData = res.data;
                }
            }
        },
        // 移除图片
        handleRemove(file) {
            // 需要删除的图片路径
            const picPath = file.url;
            // 获取该图片路径在图片数组中的索引
            const i = this.editGoodsForm.pics.findIndex(obj => {
                return obj.url === picPath;
            });
            // 在图片数组中移除该图片
            this.editGoodsForm.pics.splice(i, 1);
        },
        // 预览图片
        handlePreview(file) {
            // 需要预览的图片路径
            this.picPerviewPath = file.url;
            // 显示图片预览对话框
            this.picPerviewDialogVisible = true;
        },
        // 图片上传成功时触发
        handleSuccess(response) {
            if (response.meta.status !== 200) return this.$message.error('图片上传失败');
            // 拼接图片信息
            const picInfo = { name: response.data.tmp_path, url: response.data.url }
            this.editGoodsForm.pics.push(picInfo);
        },
        // 编辑商品
        async edit() {
            this.editGoodsForm.goods_cat = this.editGoodsForm.goods_cat.join(',')
            // 处理动态参数
            this.goodsManyData.forEach(item => {
                const newInfo = {
                    attr_id: item.attr_id,
                    attr_value: item.attr_vals.join(' ')
                }
                this.editGoodsForm.attrs.push(newInfo);
            })
            // 处理静态属性
            this.goodsOnlyData.forEach(item => {
                const newInfo = {
                    attr_id: item.attr_id,
                    attr_value: item.attr_vals
                }
                this.editGoodsForm.attrs.push(newInfo);
            })
            // 处理图片
            this.picsData.forEach(item => {
                const picInfo = {
                    pic: item.name
                }
                this.editGoodsForm.pics.push(picInfo)
            })
            const { data: res } = await this.$http.put(`goods/${this.goodsId}`, this.editGoodsForm);
            if (res.meta.status !== 200)
                return this.$notify.error({
                    title: '商品编辑失败',
                    message: '您可联系网站作者进行解决   www.h1234.top',
                    duration: 5000
                });
            this.$message.success('商品编辑成功');
            this.$router.push('/goods');
        }
    },
    computed: {
        // 计算三级分类id
        cateId() {
            if (this.editGoodsForm.goods_cat.length === 3) {
                return this.editGoodsForm.goods_cat[2];
            }
            return null;
        }
    }
}
</script>

<style lang="less" scoped>
.el-checkbox {
    margin: 0 10px 0 0 !important;
}
</style>
